package com.mooc.ppjoke.provider;

import android.content.Context;

import androidx.room.Room;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.SPUtils;
import com.bw.baseapplication_sdk.BaseApplication;
import com.bw.common.entity.RoomUserEntity;
import com.bw.common.provider.LoginProvider;
import com.bw.network_sdk.entity.BaseEntity;
import com.mooc.ppjoke.loginroom.LoginDataBase;

import java.util.List;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

@Route(path = "/login/loginimpl")
public class LoginProviderImpl implements LoginProvider {
    private LoginDataBase loginDataBase = null;
    private Observable<BaseEntity> observable;

    @Override
    public boolean isLogin() {
        return SPUtils.getInstance().getBoolean("isLogin", false);
    }

    @Override
    public Observable<BaseEntity> getUserInfo() {
        return observable;
    }

    @Override
    public void init(Context context) {
        loginDataBase = Room.databaseBuilder(BaseApplication.getInstance(), LoginDataBase.class, "login.db").build();
        Maybe<List<RoomUserEntity.InsertUserValuesEntity>> listMaybe = loginDataBase.getLoginDao().queryLogin();
        observable = listMaybe.flatMapObservable(new Function<List<RoomUserEntity.InsertUserValuesEntity>, ObservableSource<? extends BaseEntity>>() {
            @Override
            public ObservableSource<? extends BaseEntity> apply(@NonNull List<RoomUserEntity.InsertUserValuesEntity> insertUserValuesEntities) throws Exception {
                RoomUserEntity roomUserEntity = new RoomUserEntity();
                roomUserEntity.data = new RoomUserEntity.InsertUserValueEntity();
                roomUserEntity.data.data = insertUserValuesEntities.get(insertUserValuesEntities.size() - 1);
                Observable<RoomUserEntity> just = Observable.just(roomUserEntity);
                return just.map(new Function<RoomUserEntity, BaseEntity>() {
                    @Override
                    public BaseEntity apply(@NonNull RoomUserEntity roomUserEntity) throws Exception {
                        return roomUserEntity;
                    }
                });
            }
        });
    }
}
